package com.ruoyi.framework.converter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 最爱喝兽奶
 * @create 2022/7/28
 **/
@Component
public class StringToDateConverter implements Converter<String, Date> {

///    @Value("${business.date.format}")
    private String[] formats;

    @Override
    public Date convert(String source) {
        formats = new String[]{"yyyy-MM-dd hh:mm:ss"};
        for (int i = 0; i < formats.length; i++) {
            SimpleDateFormat sdf = new SimpleDateFormat(formats[i]);
            try {
                // 转换成功直接返回
                Date parse = sdf.parse(source);
                return parse;
            } catch (ParseException e) {
                if (i == formats.length - 1) {
                    // 如果最后一个转换器还是失败，就报出前端传入时间字符串格式错误异常
                    throw new RuntimeException("传入了不能被解析的时间格式字符串");
                }
            }
        }
        return null;
    }
}
